package com.lzxr.test.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import cn.hutool.db.sql.Query;
import com.lzxr.test.entity.User;
import com.lzxr.test.exception.UserException;
import com.lzxr.test.service.UserService;
import com.lzxr.test.utils.enums.UserEnum;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    public UserServiceImpl() {
    }

    public User login(User user) {
        User u = this.getUser(user);
        if (u == null) {
            // 用户不存在
            throw new UserException(UserEnum.NOT_FOUND);
        } else {
            String password = user.getPassword();
            String md5Pass = DigestUtil.md5Hex(password);
            // 验证密码正确性
            if (!md5Pass.equals(u.getPassword())) {
                throw new UserException(UserEnum.PASSWORD_ERROR);
            } else {
                // 登录成功后将密码字段清空返回用户信息
                u.setPassword("");
                return u;
            }
        }
    }

    public boolean reg(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (username != null && !username.isEmpty()) {
            if (password != null && !password.isEmpty()) {
                User u = this.getUser(user);
                // 若用户名已存在则不允许注册
                if (u != null) {
                    throw new UserException(UserEnum.USER_EXIST);
                } else {
                    // 密码进行非对称加密存储
                    user.setPassword(DigestUtil.md5Hex(password));
                    boolean ret = false;
                    try {
                        int r = Db.use().insert(Entity.create("user").parseBean(user));
                        ret = r == 1;
                        return ret;
                    } catch (SQLException var7) {
                        throw new RuntimeException(var7);
                    }
                }
            } else {
                throw new UserException(UserEnum.PASSWORD_EMPTY);
            }
        } else {
            throw new UserException(UserEnum.USERNAME_EMPTY);
        }
    }

    public User getUser(User user) {
        User ret = null;

        try {
            ret = (User)Db.use().find(Query.of(Entity.create("user").set("username", user.getUsername())), new BeanHandler(User.class));
            return ret;
        } catch (SQLException var4) {
            throw new RuntimeException(var4);
        }
    }
}
